package replicant1;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.xml.bind.DatatypeConverter;

/*
 * Player class for data structrual in server database
 */
public class Player implements java.io.Serializable {
	public String firstName;
	public String lastName;
	public int age;
	public String userName;
	public String password;
	public String iPAddress;
	public boolean statusOnline;

	/*
	 * constructor in player
	 */
	public Player() {
		statusOnline = false;
	}

	/*
	 * set this player status to signin if he/she is not sign in
	 */
	public synchronized boolean signIn() {
		if (!statusOnline) {
			statusOnline = true;
			return true;
		}
		return false;
	}

	/*
	 * set this player status to signout if he/she is not sign out
	 */
	public synchronized boolean signOut() {
		if (statusOnline) {
			statusOnline = false;
			return true;
		}
		return false;
	}

	/*
	 * get the current status of this player
	 */
	public synchronized boolean getStatus() {
		return statusOnline;
	}

	

	public static String serilizeToString(Player o) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos;
		try {
			oos = new ObjectOutputStream(baos);
			oos.writeObject(o);
			oos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String ret = DatatypeConverter.printBase64Binary(baos.toByteArray());
		//System.out.println("ser:"+ret);
		//System.out.println("ser:"+ret.length());
		return ret;
	}

	public static Player DeserializeToPlayer(String s)  {
		ByteArrayInputStream bais = new ByteArrayInputStream(
				DatatypeConverter.parseBase64Binary(s));
		//System.out.println("ser:"+s);
		//System.out.println("ser:"+s.length());
		
		Player o = null;
		try {
			ObjectInputStream ois = new ObjectInputStream(bais);
			o = (Player)ois.readObject();
			ois.close();
		} catch (ClassNotFoundException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return o;
	}

}
